import { FlowCustomNode } from '@/types'
import { Edge, FlowExportObject, RemoveEdges, RemoveNodes } from '@vue-flow/core'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import * as uuid from 'uuid'

interface FlowState {
  nodes: FlowCustomNode[]
  currentNode: FlowCustomNode | null
  currentEdge: Edge | null
  onClickType: 'node' | 'edge' | null
  removeNodes: RemoveNodes | null
  removeEdges: RemoveEdges | null
  flowToObj: () => FlowExportObject | null
}

export const useFlowStore = defineStore('flow', {
  state: (): FlowState => ({
    nodes: [
      {
        id: uuid.v4(),
        type: 'input',
        position: { x: 400, y: 100 },
        data: { label: '开始', type: 'inout' },
        class: 'custom-input-node'
      },
      {
        id: uuid.v4(),
        type: 'output',
        position: { x: 400, y: 600 },
        data: { label: '结束', type: 'inout' },
        class: 'custom-output-node'
      }
    ],
    currentNode: null,
    currentEdge: null,
    onClickType: null,
    removeNodes: null,
    removeEdges: null,
    flowToObj: null
  }),
  actions: {
    removeNode() {
      if (this.currentNode.data.type === 'inout') {
        ElMessage.warning('入口节点和出口节点不能删除')
        return
      }

      this.removeNodes(this.currentNode.id, true)

      this.resetOnClick()
    },
    removeEdge() {
      this.removeEdges(this.currentEdge.id)
      this.resetOnClick()
    },
    resetOnClick() {
      this.currentNode = null
      this.currentEdge = null
      this.onClickType = null
    }
  }
})
